#include "timer.h"

static unsigned long get_pclk(unsigned long cclk, unsigned long sel)
{
  if (sel == 0)
    return cclk >> 2;
  if (sel == 1)
    return cclk;
  if (sel == 2)
    return cclk >> 1;
  return cclk >> 3;
}

static unsigned long get_timer1_clk(unsigned long fosc)
{
  unsigned long cclk = liblpc2000_lpc23xx_get_cclk(fosc);
  unsigned long pclk = get_pclk(cclk, (PCLKSEL0 & PCLKSEL0_PCLK_TIMER1_MASK) >> PCLKSEL0_PCLK_TIMER1_BIT);
  return pclk;
}

void timer_enable(void)
{
}

void delay_us(unsigned int us)
{
  unsigned int c = get_timer1_clk(OSCILLATOR_CLOCK_FREQUENCY);
  T1TCR = (1<<T1TCR_Counter_Reset_BIT);           // reset & disable timer
  T1PR  = (c / 1000000)*us;                       // set the prescale divider (1 tick = 1 us)
  T1TCR = (1<<T1TCR_Counter_Enable_BIT);
  while ((c = T1TC) == 0);
  T1TCR = 0;                                      // disable timer
}

void delay_ms(unsigned int ms)
{
  delay_us(1000*ms);
}